#解析表格写入的寄存器配置, 并生成对应写入的寄存器配置文件
import os

class WriteConfigCreator:
    def __init__(self, name):
        self.name = name
        self.source_file = f"{name}.c"
        self.include_file = f"{name}.h"
        self.registers = []  # 用于存储寄存器名称和地址
        self.end_guard = f"\n#endif // __{self.name.upper()}_H__\n"
        self.format_init()
        self.function_begin = f"void {self.name}_write(unsigned char *array) {{\n"
        self.function_end = f"\n}} // {self.name}_write end\n"

    def include_file_init(self):
        # 写入头文件格式
        define_guard = f"#ifndef __{self.name.upper()}_H__\n#define __{self.name.upper()}_H__\n\n"
   
        with open(self.include_file, 'w', encoding='utf-8') as file:
            file.write(define_guard)
            file.write(self.end_guard)

    def source_file_init(self):
        # 写入源文件格式
        with open(self.source_file, 'w', encoding='utf-8') as file:
            file.write(f"#include \"{self.include_file}\"\n\n")

    def format_init(self):
        #第一次初始化
        self.include_file_init()
        self.source_file_init()

    def write_config(self, register_name, register_data):
        # 写入寄存器配置
        write_data = f"    {self.name}.{register_name}[1] = 0x{register_data:02x};\n"
        
        # 检查文件是否存在，如果不存在，则创建文件并写入函数的开始部分
        if not os.path.exists(self.source_file):
            with open(self.source_file, 'w', encoding='utf-8') as file:
                file.write(self.function_begin)
                file.write(self.function_end)
        
        # 读取现有文件内容
        with open(self.source_file, 'r+', encoding='utf-8') as file:
            content = file.read()
            # 查找函数的开始部分
            begin_index = content.find(self.function_begin)
            if begin_index != -1:
                # 移除函数的开始部分和结束部分
                content = content[:begin_index] + content[begin_index:].split(self.function_end, 1)[0]
            else:
                # 如果函数开始部分不存在，则添加它
                content += self.function_begin

            # 将新的配置行添加到函数体内
            content += write_data

            # 将函数的结束部分添加回文件
            content += self.function_end
        
        # 将修改后的内容写回文件
        with open(self.source_file, 'w', encoding='utf-8') as file:
            file.write(content)


if __name__ == '__main__':
    creator = WriteConfigCreator("test")
    creator.write_config("A", 0x0f)
    creator.write_config("B", 0x0a)
    creator.write_config("B", 0x0a)